﻿#include <iostream>
#include <cfloat>
#include "Head/Stuck.h"

template <typename T>
T safeCin(T Min, T Max);
void showmenu();
void ctrlcmpt(Stuck &);

int main()
{
    using std::cout;
    using std::endl;
    system("chcp 65001>nul");

    Item temp;
    Stuck memory;

    do
    {
        showmenu();
        int choice = safeCin(0, 3);
        switch (choice)
        {
        case 0:
            if (!(memory.full()))
            {
                cout << "请输入操作数：";
                memory.add(memory.cin());
                cout << "存入数据成功。\n";
            }
            else
                cout << "存入数据失败，栈存储空间已满。\n";
            break;
        case 1:
            if (!(memory.empty()))
            {
                cout << "请输入操作数：";
                memory.remove(temp);
                cout << "取出数据成功。数据内容：" << temp << endl;
            }
            else
                cout << "取出数据失败，栈中未存储任何内容。\n";
            break;
        case 2:
            ctrlcmpt(memory);
            break;
        case 3:
            memory.show();
            break;
        }
    if (choice == 4)
        break;
    }
    while (true);

    system ("pause");
    return 0;
};

void showmenu()
{
    using std::cout;
    cout << "欢迎您测试本栈，输入指定数字以完成请求。\n"
         << "   0 存入数据\n"
         << "   1 取出数据\n"
         << "   2 对栈中内容执行计算\n"
         << "   3 显示栈中内容\n"
         << "   4 退出程序\n";
};

void ctrlcmpt(Stuck & memory)
{
    using std::cout;

    cout << "操作栈选项：\n"
         << "   0 进行乘法运算\n"
         << "   1 进行除法运算\n";
    int choice = safeCin(0, 1);
    cout << "请输入操作数：";
    double times = safeCin(-DBL_MAX, DBL_MAX);

    if (choice == 0)
        memory.ctrl(mul, times);
    else
        memory.ctrl(div, times);
    cout << "操作完成。\n";
};

template <typename T>
T safeCin(T Min, T Max)
{
    using std::cin;
    int i_temp = 0;
    char c_temp;
    while ((!(cin >> i_temp)) || (!(i_temp >= Min && i_temp <= Max)))
    {
        cin.clear();
        while (cin.get() != '\n')
            continue;
        std::cout << "出现异常 - 请输入一个指定范围内的整数。" << "\t( " << Min << " ~ " << Max << " )" << std::endl;
    };
    return i_temp;
};